package com.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyCode.feature.mybaits.CustomPage;
import com.manager.client.CampusClient;
import com.manager.entity.dao.Campus;
import com.manager.entity.dao.Manager;
import com.manager.entity.dao.User;
import com.manager.entity.dto.CampusDto;
import com.manager.entity.dto.CampusManagerDto;
import com.manager.entity.dto.UserDto;
import com.manager.entity.vo.CampusVo;
import com.manager.exception.CampusException;
import com.manager.exception.ManagerException;
import com.manager.mapper.CampusMapper;
import com.manager.service.ICampusService;
import com.manager.service.IManagerService;
import com.manager.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.manager.entity.factory.CampusFactory.CAMPUS_CONVERTER;
import static com.manager.entity.factory.ManagerFactory.MANAGER_CONVERTER;
import static com.manager.entity.factory.UserFactory.USER_CONVERTER;

@Service
@RequiredArgsConstructor
public class CampusServiceImpl extends ServiceImpl<CampusMapper, Campus> implements ICampusService {
    @Autowired
    private IManagerService iManagerService;
    @Autowired
    private CampusClient campusClient;

    @Override
    public Integer saveCampus(CampusVo campusVo) {
        Campus campus = CAMPUS_CONVERTER.toCampus(campusVo);
        Campus.nameRepeatCheck(campus, this);
        save(campus);
        return campus.getId();
    }

    @Override
    public CampusDto getCampusById(Integer id) {
        Campus campus = getById(id);
        return CAMPUS_CONVERTER.toCampusDto(campus);
    }

    @Override
    public List<CampusDto> listCampus(CustomPage customPage) {
        List<Campus> campusList = CustomPage.getResult(customPage, new Campus(), this, null);
        return CAMPUS_CONVERTER.toListCampusDto(campusList);
    }

    @Override
    public void delCampusById(Integer id) {
        //如果当前主校区下存在课程,那么禁止删除
        if(campusClient.existCourseUnderCampus(id)){
            throw new CampusException("当前主校区下关联着课程,无法删除");
        }
        removeById(id);
    }

    @Override
    public void checkExist(Integer cId) {
        long count = count(new QueryWrapper<Campus>().eq("id", cId));
        if (count == 0) {
            throw new ManagerException("校区不存在");
        }
    }

    @Override
    public List<CampusManagerDto> listManagesOfCampus(Integer id, CustomPage customPage) {
        List<Manager> managers = CustomPage.getResult(customPage, new Manager(), iManagerService, new QueryWrapper<Manager>().eq("c_id", id));
        return MANAGER_CONVERTER.toListCampusManagerDto(managers);
    }
}
